package com.lcsuo.credit.service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lcsuo.credit.dao.CompanysummaryMapper;
import com.lcsuo.credit.entity.CompanySummary;

@Service
public class CompanysummaryService {
	
	public static final String COMPANYSUMMARY_LIST ="companysummary_list";
	public static final String COMPANYCODE ="440301109038824";
	
	private static final Logger log = Logger.getLogger(CompanysummaryService.class);
	
	@Autowired
	private StringRedisTemplate  redisTemplate ;
	
	@Autowired
	private RedissonClient redissonClient;
	
	public static final DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); 

	@Autowired
	private CompanysummaryMapper companySummaryMapper;
	ObjectMapper om = new ObjectMapper();
	
	/**
	 * 更新账户时加入分布式锁
	 * @param companyCode
	 * @param balance
	 * @return
	 */
	public boolean updateBalance(String companyCode,BigDecimal balance) {
		RLock lock = null;
		try {
			lock = redissonClient.getLock(COMPANYCODE);
			if(companySummaryMapper.update(companyCode, balance,  LocalDateTime.now().format(format)) >0 ) {
				return true;
			}
			return false;
		} finally  {
			lock.unlock();
		}
	}
	
	

	public List<CompanySummary> findAll() throws Exception{
		List<CompanySummary> listCompanySummary = null;
		 String list = (String) redisTemplate.opsForValue().get(COMPANYSUMMARY_LIST);
		 if(list==null) {
			 log.debug("=======================mysql findAll");
			 listCompanySummary = companySummaryMapper.findAll();
			 redisTemplate.opsForValue().set(COMPANYSUMMARY_LIST, om.writeValueAsString(listCompanySummary), 3, TimeUnit.MINUTES);
		 }else {
				listCompanySummary = om.readValue(list, List.class);
		 }
		return listCompanySummary;
	}
	
	public CompanySummary findByCompanyCode(String companycode) {
		return companySummaryMapper.findByCompanyCode(companycode);
	}
	
	
}
